/**
 * weapp-js v2.2.3(2022-4-26)
 * https://codeup.aliyun.com/motigo/motigo/weapp_base
 * Copyright@ 2022 Motigo, Inc.
 * 
 */
import Theme from '../../theme';

Component({
    data: {
        visible: false,
        contentVisible: false,
        logo: Theme.login.logo,
        title: '',
        loginBtnColor: Theme.login.loginBtnColor,
        canIUseGetUserProfile: false,
    },
    callbackSuccess: null,
    callbackFail: null,
    methods: {
        stopEvent() {},
        _close(errCode, errMsg) {
            this.setData({
                visible: false,
            });

            this.callbackFail &&
                this.callbackFail({
                    errCode: errCode,
                    errMsg: errMsg || '未知错误',
                });
        },
        onCancel() {
            this._close('CANCEL', 'canceled');
        },
        login(opts) {
            if (wx.getUserProfile) {
                this.setData({
                    canIUseGetUserProfile: true,
                });
            }

            this.setData({
                visible: true,
                title: opts.title || '请完成微信授权以继续使用',
            });

            // 等根节点显示出来下一帧再显示contentl
            wx.nextTick(() => {
                this.setData({
                    contentVisible: true,
                });
            });

            return new Promise((resolve, reject) => {
                this.callbackSuccess = resolve;
                this.callbackFail = reject;
            });
        },
        // 点击了“登录”，待废弃，微信废弃了wx.getUserInfo接口
        // https://developers.weixin.qq.com/community/develop/doc/000cacfa20ce88df04cb468bc52801
        onLogin(evt) {
            const detail = evt.detail;

            if (detail.errMsg === 'getUserInfo:ok') {
                this._onGetUserInfo(detail.userInfo);
            } else {
                this._close('CANCEL', detail.errMsg);
            }

        },
        _onGetUserInfo(userInfo) {
            console.log('_onGetUserInfo');
            console.log(userInfo);
            this.setData({
                contentVisible: false,
                visible: false,
            });

            // Session._setSessionCache(userInfo);
            this.callbackSuccess && this.callbackSuccess(userInfo);
        },
        onGetUserProfile() {
            wx.getUserProfile({
                desc: '用于完善您的信息',
                success: (res) => {
                    console.log('success getUserProfile', res);
                    this._onGetUserInfo(res.userInfo);
                },
                fail: (res) => {
                    console.log('fail getUserProfile', res);
                    this._close('CANCEL', res.errMsg);
                },
            });

        },
    },
});
